/* global wps */
import {useEffect, useState} from 'react';
import axios from 'axios';

function App() {
  let [hasSelectionListener, setHasSelectionListener] = useState(false);
  let [selection, setSelection] = useState(null);
  let [users, setUsers] = useState([]);

  const onClickInsertParagraph = () => {
    wps.Application.Selection.InsertAfter(new Date().toLocaleString() + '\n');
    wps.Application.Selection.Collapse(wps.Application.Enum.wdCollapseEnd)
  };

  const onAddWindowSelectionChange = () => {
    setHasSelectionListener(true);
    wps.Application.ApiEvent.AddApiEventListener("WindowSelectionChange", selection => {
      // console.log('selection: ', selection);
      setSelection(selection.Text);
    });
  };

  const onRemoveWindowSelectionChange = () => {
    setHasSelectionListener(false);
    wps.Application.ApiEvent.RemoveApiEventListener("WindowSelectionChange");
  }

  useEffect(() => {
    return () => {
      wps.Application.ApiEvent.RemoveApiEventListener("WindowSelectionChange")
    };
  }, []);

  const onSendNetRequest = async () => {
   let users = await axios.get('https://jsonplaceholder.typicode.com/users');
   setUsers(users.data);
  }

  return (
    <div>
      <h1>cra创建的WPS插件demo</h1>
      <h2>test 插件调用WPS API</h2>
      <div>
        <div>
          <button onClick={onClickInsertParagraph}>文档中插入当前时间</button>
        </div>
      </div>
      <h2>test 监听WPS的事件</h2>
      <div>
          {!hasSelectionListener ? (
            <button onClick={onAddWindowSelectionChange}>开启监听文档中光标选中内容的变化</button>
          ): (
            <>
              <button onClick={onRemoveWindowSelectionChange}>停止监听文档中光标选中内容的变化</button>
              <div>
                选中内容：{selection}
              </div>
            </>
          )}
      </div>
      <h2>test 网络通信</h2>
      <div>
        <div>使用在线fake API<a href="https://jsonplaceholder.typicode.com/">JSON Placeholder</a></div>
        <div>
          <button onClick={onSendNetRequest}>获取用户列表</button>
        </div>
        <div>
          {users.map(user => {
            return (
              <div key={user.id} style={{border: '1px solid blue', marginBottom: '5px'}}>
                <div>{user.username}</div>
                <div>{user.address.street}</div>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  );
}

export default App;
